package com.icefish.control;

import com.alibaba.fastjson.JSONObject;
import com.icefish.bean.Good;
import com.icefish.bean.fastjsonParse.Meta;
import com.icefish.bean.fastjsonParse.getAllGoods.GetAllGoodsResp;
import com.icefish.dao.GoodDao;
import com.icefish.daoFactory.DaoFactory;
import com.icefish.utils.Init_Req_Resp_Config;
import com.icefish.utils.JWT_Utile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/getAllGoods")
public class getAllGoods extends HttpServlet {

    private GoodDao goodDao = DaoFactory.getGoodDaoInstance();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 标准配置
        Init_Req_Resp_Config.init(request, response);


        Boolean getAllFlag = null;
        Meta meta = null;
        GetAllGoodsResp getAllGoodsResp = new GetAllGoodsResp();

        try {
            //获取所有商品数据
            List<Good> goodList = goodDao.selectGoodList();
            getAllGoodsResp.setData(goodList);

            //判断数据是否获取正常
            if(getAllGoodsResp.getData()!=null)
                getAllFlag=true;

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (getAllFlag) {
            //如果数据获取正常，创建meta对象并赋值给getAllGoodsResp的Meta部分
            meta = new Meta("获取商品信息成功",200);
            getAllGoodsResp.setMeta(meta);
        } else {
            // 获取失败
            meta = new Meta("获取商品信息失败",200);
            getAllGoodsResp.setMeta(meta);
        }

        //相应Json数据
        JSONObject jsonObject = new JSONObject();
        // 转换成json
        String backToBrowser = jsonObject.toJSONString(getAllGoodsResp);

        // 响应数据
        response.getWriter().write(backToBrowser);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}